/**
 * 智慧小区管理系统 - 简化权限管理 Store
 * 
 * 权限控制粒度简化：
 * - 移除按钮权限管理
 * - 保留菜单权限管理
 * - 简化权限验证逻辑
 * 
 * @author Wu.Liang
 * @date 2024-01-01
 * @updated 2025-01-30 - 简化权限管理，移除复杂的权限获取逻辑
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from './user'
import { STATUS } from '@/constants/enums'
import { ROLE_CODES } from '@/constants/roles'

interface MenuPermission {
    id: number
    name: string
    code: string
    type: 'menu'
    parentId?: number
    path?: string
    component?: string
    icon?: string
    sort?: number
    status: number
    children?: MenuPermission[]
}

interface Role {
    id: number
    name: string
    code: string
    description?: string
    status: number
}

export const usePermissionStore = defineStore('permission', () => {
    // 状态数据
    const menuPermissions = ref<MenuPermission[]>([])
    const roles = ref<Role[]>([])
    const accessedRoutes = ref<RouteRecordRaw[]>([])
    const menuPermissionCodes = ref<string[]>([])
    const permissionCache = ref<Map<string, boolean>>(new Map())
    const lastPermissionUpdate = ref<number>(0)
    const isInitialized = ref(false)

    // 计算属性
    const permissionTree = computed(() => {
        return buildPermissionTree(menuPermissions.value)
    })

    const menuTree = computed(() => {
        return menuPermissions.value
            .filter(p => p.type === 'menu' && p.status === STATUS.ENABLED)
            .sort((a, b) => (a.sort || 0) - (b.sort || 0))
    })

    const allMenuPermissions = computed(() => {
        return menuPermissionCodes.value
    })

    // 菜单权限检查方法
    const hasMenuPermission = (menuCode: string): boolean => {
        const userStore = useUserStore()

        // 超级管理员拥有所有菜单权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            // console.log('权限检查: 超级管理员权限通过 -', menuCode)
            return true
        }

        // 只做只读判断，不做任何初始化
        if (!menuPermissionCodes.value || menuPermissionCodes.value.length === 0) {
            // console.warn('权限检查: 权限列表为空 -', menuCode)
            return false
        }

        // 检查缓存
        if (permissionCache.value.has(menuCode)) {
            const cachedResult = permissionCache.value.get(menuCode)!
            // console.log('权限检查: 使用缓存结果 -', menuCode, '结果:', cachedResult)
            return cachedResult
        }

        // 检查是否有该菜单权限
        const hasMenuPerm = menuPermissionCodes.value.includes(menuCode)
        // 缓存结果
        permissionCache.value.set(menuCode, hasMenuPerm)
        // console.log('权限检查: 检查结果 -', menuCode, '结果:', hasMenuPerm, '用户权限列表:', menuPermissionCodes.value)
        return hasMenuPerm
    }

    const hasRole = (role: string): boolean => {
        const userStore = useUserStore()
        return userStore.userRoles.includes(role)
    }

    // 从用户信息初始化权限 - 修复版本
    const initPermissionsFromUserInfo = async (): Promise<boolean> => {
        console.log('开始初始化权限信息...')
        
        const userStore = useUserStore()
        
        // 等待用户信息完全加载
        if (!userStore.userInfo) {
            console.warn('用户信息未加载，无法初始化权限')
            menuPermissionCodes.value = []
            isInitialized.value = false
            return false
        }
        
        if (userStore.userInfo.permissions) {
            menuPermissionCodes.value = [...userStore.userInfo.permissions]
            lastPermissionUpdate.value = Date.now()
            isInitialized.value = true
            // 不要每次都清理缓存，只在必要时清理
            console.log('从用户信息初始化权限成功:', menuPermissionCodes.value.length, '个权限')
            return true
        } else {
            console.warn('用户信息中无权限数据')
            menuPermissionCodes.value = []
            isInitialized.value = false
            return false
        }
    }

    // 检查权限是否过期
    const isPermissionExpired = (): boolean => {
        // 权限缓存30分钟过期
        const expireTime = 30 * 60 * 1000 // 30分钟
        return Date.now() - lastPermissionUpdate.value > expireTime
    }

    // 构建权限树
    const buildPermissionTree = (permissions: MenuPermission[]): MenuPermission[] => {
        const permissionMap = new Map<number, MenuPermission>()
        const rootPermissions: MenuPermission[] = []

        // 创建权限映射
        permissions.forEach(permission => {
            permissionMap.set(permission.id, { ...permission, children: [] })
        })

        // 构建树形结构
        permissions.forEach(permission => {
            const node = permissionMap.get(permission.id)!
            if (permission.parentId && permission.parentId !== 0) {
                const parent = permissionMap.get(permission.parentId)
                if (parent) {
                    if (!parent.children) {
                        parent.children = []
                    }
                    parent.children.push(node)
                }
            } else {
                rootPermissions.push(node)
            }
        })

        return rootPermissions
    }

    // 检查路由权限
    const hasRoutePermission = (route: RouteRecordRaw, roles: string[]): boolean => {
        const requiredPermission = route.meta?.permission as string
        if (!requiredPermission) {
            return true
        }
        return hasMenuPermission(requiredPermission)
    }

    // 获取菜单权限 - 简化版本，直接从用户信息获取
    const getMenuPermissions = async (userRoles: string[], forceRefresh: boolean = false) => {
        const userStore = useUserStore()
        
        // 未登录直接return
        if (!userStore.isLogged) {
            console.warn('用户未登录，无法获取菜单权限')
            return
        }

        // 权限已加载且未过期且非强制刷新，直接返回
        if (!forceRefresh && !isPermissionExpired() && menuPermissionCodes.value.length > 0) {
            return
        }

        // 从用户信息中获取权限
        await initPermissionsFromUserInfo()
    }

    // 强制刷新权限
    const forceRefreshPermissions = async (userRoles: string[]) => {
        const userStore = useUserStore()
        if (!userStore.isLogged) {
            return
        }
        await getMenuPermissions(userRoles, true)
    }

    // 从本地存储加载权限
    const loadPermissionsFromStorage = () => {
        try {
            const stored = localStorage.getItem('menuPermissions')
            if (stored) {
                const data = JSON.parse(stored)
                menuPermissions.value = data.permissions || []
                menuPermissionCodes.value = data.codes || []
                lastPermissionUpdate.value = data.timestamp || 0
                isInitialized.value = true
                console.log('从本地存储加载菜单权限数据成功')
            }
        } catch (error) {
            console.error('从本地存储加载菜单权限数据失败:', error)
        }
    }

    // 保存权限到本地存储
    const savePermissionsToStorage = () => {
        try {
            const data = {
                permissions: menuPermissions.value,
                codes: menuPermissionCodes.value,
                timestamp: lastPermissionUpdate.value
            }
            localStorage.setItem('menuPermissions', JSON.stringify(data))
            console.log('菜单权限数据保存到本地存储成功')
        } catch (error) {
            console.error('保存菜单权限数据到本地存储失败:', error)
        }
    }

    // 重置权限
    const resetPermissions = () => {
        menuPermissions.value = []
        menuPermissionCodes.value = []
        accessedRoutes.value = []
        permissionCache.value.clear()
        lastPermissionUpdate.value = 0
        isInitialized.value = false
        
        // 清除本地存储
        localStorage.removeItem('menuPermissions')
        
        console.log('权限数据已重置')
    }

    // 刷新权限缓存
    const refreshPermissionCache = () => {
        permissionCache.value.clear()
        console.log('权限缓存已刷新')
    }

    // 添加访问路由
    const addAccessedRoute = (route: RouteRecordRaw) => {
        if (!accessedRoutes.value.find(r => r.path === route.path)) {
            accessedRoutes.value.push(route)
        }
    }

    // 设置访问路由
    const setAccessedRoutes = (routes: RouteRecordRaw[]) => {
        accessedRoutes.value = routes
    }

    // 获取访问路由
    const getAccessedRoutes = (): RouteRecordRaw[] => {
        return accessedRoutes.value
    }

    // 清除访问路由
    const clearAccessedRoutes = () => {
        accessedRoutes.value = []
    }

    return {
        // 状态
        menuPermissions,
        roles,
        accessedRoutes,
        menuPermissionCodes,
        permissionCache,
        lastPermissionUpdate,
        isInitialized,

        // 计算属性
        permissionTree,
        menuTree,
        allMenuPermissions,

        // 方法
        hasMenuPermission,
        hasRole,
        getMenuPermissions,
        forceRefreshPermissions,
        loadPermissionsFromStorage,
        savePermissionsToStorage,
        resetPermissions,
        refreshPermissionCache,
        addAccessedRoute,
        setAccessedRoutes,
        getAccessedRoutes,
        clearAccessedRoutes,
        initPermissionsFromUserInfo,
        isPermissionExpired
    }
})
